# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: webserver.py
Author: kij
Create Date: 2021/3/1
-------------------------------------------------
"""
import os
import sys
import socket

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from conn.conn_client import NetDataUtils
from conn import setting
from fileoperate import User


def start_server():
	print("服务器数据启动".center(50, "*"))
	# 新建socket对象
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	# 绑定端口和ip 元组类型端口为整型
	sock.bind((setting.HOST, setting.PORT))
	# 设置最大连接数
	sock.listen(setting.MAX_SOCKET_LISTEN)
	while True:
		# 开始链接客户端
		conn, addr = sock.accept()
		print("链接成功")
		net_data = NetDataUtils(conn)
		# 接收到用户后先发送可以链接了
		net_data.send_client(action_type='start', code=setting.SUCCESS, msg='链接成功')
		try:
			while True:
				has_func, hint = net_data.switch_request()
				# 客户端不接收数据后断开
				print(hint)
				if not has_func:
					break
		except Exception as e:
			print(".", e)
			conn.close()

	sock.close()


def regiser_user():
	'''注册用户'''
	print('Q/q退出')
	user_name = input('用户名:')
	if user_name.upper() == 'Q':
		run()
	user_password = input('密码:')
	size = input('容量:')
	user = User(user_name, user_password,size)
	is_success, hint = user.register_user(setting.ACCOUNT_FILE)
	if is_success:
		print(hint)
		run()
	else:
		print(hint)
		regiser_user()


def run():
	'''注册或者启动服务器'''
	try:
		select = input('输入1.注册 ，任意输入启动服务器>>>').strip()
		if select == '1':
			'''注册'''
			regiser_user()
		else:
			'''启动'''
			start_server()
	except KeyboardInterrupt as e:
		exit('退出系统')



if __name__ == "__main__":
	run()
